let that = this;


//////////////////////
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 检查表单数据是否符合正则，所有参数都通过返回false，否则返回true
 * @param  数组参数
 */
function check(...args) {
  if (args.length == 0) return false;
  let isWrong = false;
  args.forEach(v => {
    if (!Array.isArray(v) || v.length < 3) return;
    let data = v[0],
      reg = v[1],
      msg = v[2];
    if (reg == "phone") {
      reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})))+\d{8}$/
    } else if (reg == "name") {
      reg = /^[\u4E00-\u9FA5]{2,4}$/
    } else if (reg == "number") {
      reg = /^(0|([1-9]\d*))(\.\d+)?$/
    } else if (reg == "nospace") {
      reg = /\S+/
    } else if (reg instanceof RegExp) {
      reg = reg
    }
    //两种判断
    if (typeof data == "boolean") {
      if (!data) {
        console.log(data, reg, 11);
        wx.showToast({
          title: msg,
          icon: "none",
          duration: 3000
        });
        isWrong = true;
        return;
      }
    } else if (typeof data == "string") {
      console.log(data, typeof reg, 33);
      if (!reg.test(data)) {
        console.log(data, reg, 22);
        wx.showToast({
          title: msg,
          icon: "none",
          duration: 3000
        });
        isWrong = true;
        return;
      }

    } else console.error("数组第一参数需为字符串或布尔值");
  })
  return isWrong;
}
/* let openid = app.util.getopenid.call(this, "pages");
if (!openid) return; */
const getopenid = function (data) {
  data = data || false;
  var t = this;
  let openid = wx.getStorageSync("openid")
  if (!openid) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              // app.globalData.userInfo = res.userInfo
              wx.login({
                success: res => {
                  //res.code
                }
              })
            }
          })
        } else {
          if (/\/pages\//.test(data)) {
            wx.navigateTo({
              url: data
            })
            wx.showToast({
              title: "没有获取到授权",
              icon: "none"
            })
          } else if (data) {
            t.setData({
              [data]: true
            })
          }
        }
      }
    });
  }
  return openid;
}
const getQuery = function (e) {
  var t = [];
  if (-1 != e.indexOf("?"))
    for (var n = e.split("?")[1].split("&"), a = 0; a < n.length; a++) n[a].split("=")[0] && unescape(n[a].split("=")[
      1]) &&
      (t[a] = {
        name: n[a].split("=")[0],
        value: unescape(n[a].split("=")[1])
      });
  return t;
}

function getQueryValue(e, t) {
  var n = new RegExp("(^|&)" + t + "=([^&]*)(&|$)"),
    a = e.split("?")[1].match(n);
  return null != a ? unescape(a[2]) : null;
}
const debounce = function (fn, delay) {
  var timer;
  return function () {
    var _this = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    if (!timer) {
      fn.apply(_this, args);
    }
    timer = setTimeout(function () {
      timer = null;
    }, delay);
  };
}




const richText = function (e) {
  e = e || "";
  return e.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ').replace(/<section/g, '<div').replace(
    /\/section>/g, '/div>');
}

const likeNum = function (e) {
  e = e * 1 || 0
  return e > 10000 ? (Math.floor(e / 1000) / 10 + "万") : e;
}

const str2Date = function (s) {
  if (s.length == 8) // yyyyMMdd
    return new Date(s.substr(0, 4) + '/' + s.substr(4, 2) + "/" + s.substr(6, 2));
  s = s.replace(/-/g, "/");
  s = s.replace(/(\.\d+)?/g, "");
  var date = new Date(s);
  return date;
}



const wxWebsocket = function (url, data) {
  return wx.connectSocket({
    url: url,
    // data: data,
    /*   header: {
        'content-type': 'application/x-www-form-urlencoded'
      },  */
    method: 'post',
    success: res => {
      console.log('WebSocket connect', res);
    },
    fail: err => {
      console.log('出现错误啦！！' + err);
      wx.showToast({
        title: '网络异常！',
      })
    }
  })
}

/**
 * 根据范围获取随机字符串（数字+字母），一个参数时固定长度字符串
 * @param {Object} min 范围最小值
 * @param {Object} max范围最大值
 */
const getNonce = function (min, max) {
  var str = "",
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
      'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
      'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    ];
  // 随机产生
  var range = max != undefined ? Math.round(Math.random() * (max - min + 1)) + min : min;
  let pos = 0;
  for (var i = 0; i < range; i++) {
    pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}

/** 
 * form的submit事件参数获取
*/
const getSubmitData=function(e){
  let i = 0,
    obj = {};
  while (e.target[i]) {
    if (e.target[i].name) obj[e.target[i].name] = e.target[i].value;
    i++;
  }
  return obj;
}

/**
 * 获取随机数（整数）
 * @param {Object} minNum随机范围最小值
 * @param {Object} maxNum  随机范围最大值
 */
const getRandom = function (minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      //或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
      break;
    default:
      return 0;
      break;
  }
}
/* const xxx = function(){

} */
import apiz from './api.js';
import md5 from "./md5.js";
/**
 * api封装
 */
const api = function (method = "get", url = "/", data = {}, set) {
  function getNonce(min, max) {
    var str = "",
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
        'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
        'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ];
    // 随机产生
    var range = max != undefined ? Math.round(Math.random() * (max - min + 1)) + min : min;
    let pos = 0;
    for (var i = 0; i < range; i++) {
      pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  }
  let urlz = `http://slp1.slzrsz.com:8888/api${url}`,
    timeStamp = String(+new Date()).slice(0, 10),
    nonce = getNonce(10),
    APPID = 'slzrweapp',
    APPTYPE = 'WEAPP',
    APPKEY = 'A0E6C376000F44AEF13F58614C379DD9',
    signStr =
      `AppId=${APPID}&AppKey=${APPKEY}&AppType=${APPTYPE}&Data=${encodeURIComponent(JSON.stringify(data))}&Nonce=${nonce}&TimeStamp=${timeStamp}&Url=${urlz}`
  const opt = {
    Appid: APPID,
    AppType: APPTYPE,
    Data: data,
    Nonce: nonce,
    SignType: 'MD5',
    SignVersion: '1.1',
    Signature: md5(signStr),
    TimeStamp: timeStamp,
    Url: urlz
  }
  apiz.api(method, url, opt, set)
}
const post = (url, data, set) => api('post', url, data, set);
const get = (url, data, set) => api('get', url, data, set);
import wxUtils from "./wxUtils.js";

export default {
  api,
  post,
  get,
  ...wxUtils,
  getRandom,
  formatTime: formatTime,
  debounce,
  getNonce,
  check,
  getSubmitData,
  str2Date,
  getopenid,
  richText,
  getQuery,
  getQueryValue,
  likeNum,
  wxWebsocket
}
